package game.network;

import game.Model;
import game.Player;

import java.net.*;
import java.io.*;

public class ServerThread implements Runnable {

	private Model model;

	public ServerThread(Model network) {
		this.model = network;
	}

	public void run() {
		ServerSocket serverSocket = null;
		OutputStream os = null;
		ObjectOutputStream oos = null;
		InputStream is = null;
		ObjectInputStream ois = null;
		try {
			serverSocket = new ServerSocket(4444);			
			System.out.println("server: waiting for the client to connect");
			Socket clientSocket = serverSocket.accept();
			clientSocket.setTcpNoDelay(true);
			System.out.println("server: client connected");
			is = clientSocket.getInputStream();
			ois = new ObjectInputStream(is);
			os = clientSocket.getOutputStream();
			oos = new ObjectOutputStream(os);
			while (model.isNetworkWorking()) {
				Packet packet = ClientThread.receivePacket(ois);
				model.setPacket(packet);
				
				Player me = model.getMyPlayer();
				if (me != null) {
					ClientThread.sendPacket(oos, model.getPacket());																																					
				}
				//System.out.println("server: sent the cords: " + myCords);
				Thread.sleep(10);
			}
			os.close();
			oos.close();
			is.close();
			ois.close();
			clientSocket.close();
			serverSocket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
